package com.hzhk.happyrent.ui.view;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hzhk.happyrent.Constants;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.UpdateModel;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.TimeUtil;
import com.tamic.novate.Throwable;
import com.tamic.novate.download.DownLoadCallBack;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ss on 2017/12/24.
 */

public class UpdateView {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_msg)
    TextView txtMsg;
    @BindView(R.id.txt_msg2)
    TextView txtMsg2;
    @BindView(R.id.txt_msg3)
    TextView txtMsg3;
    @BindView(R.id.btn_neg)
    Button btnNeg;
    @BindView(R.id.img_line)
    ImageView imgLine;
    @BindView(R.id.btn_pos)
    Button btnPos;
    @BindView(R.id.lLayout_bg)
    LinearLayout lLayoutBg;
    @BindView(R.id.firstBar)
    ProgressBar firstBar;
    private Context context;
    private View popView;
    private Dialog dialog;
    private boolean updateForce=false;
    private String url;
    private boolean isUpdateing=false;


    public UpdateView(Context context) {
        this.context = context;
    }

    public void build(UpdateModel updateModel) {
        dialog = new Dialog(context, R.style.AlertDialogStyle);
        popView = ((Activity) context).getLayoutInflater().inflate(R.layout.view_update, null);
        ButterKnife.bind(this, popView);
        intView(updateModel);
        //获取屏幕宽
        int weight = context.getResources().getDisplayMetrics().widthPixels * 4 / 5;
        dialog.setCancelable(false);
        dialog.setContentView(popView);
        popView.setLayoutParams(new FrameLayout.LayoutParams(weight, FrameLayout.LayoutParams.WRAP_CONTENT));
        dialog.show();
    }

    private void intView(UpdateModel updateModel) {
        if(!TextUtils.isEmpty(updateModel.getData().getName())){
            txtMsg.setText("版本号："+updateModel.getData().getName());
        }
        if(!TextUtils.isEmpty(updateModel.getData().getUpdatedAt())){
            txtMsg2.setText("更新时间："+TimeUtil.getStrTime(updateModel.getData().getUpdatedAt()));
        }
        if(!TextUtils.isEmpty(updateModel.getData().getDesc())){
            txtMsg3.setText(updateModel.getData().getDesc());
        }
        if("1".equals(updateModel.getData().getAndroidNeedUpgrade())){
            btnNeg.setText("退出");
            updateForce=true;
        }
        if(!TextUtils.isEmpty(updateModel.getData().getDownUrl())){
            url=updateModel.getData().getDownUrl();
        }

    }

    @OnClick({R.id.btn_neg, R.id.btn_pos})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_neg:
                if(updateForce){
                    dialog.dismiss();
                    ((Activity)context).finish();
                }else{
                    dialog.dismiss();
                }
                break;
            case R.id.btn_pos:
                if(!TextUtils.isEmpty(url)){
                    String download_apk = MyPerference.getInstance().getString(Constants.DOWNLOAD_APK, "");
                    if(!TextUtils.isEmpty(download_apk)){
                        File f=new File(download_apk);
                        if(f.exists()&&download_apk.equals(url))
                        {
                            doIntent("file://"+ download_apk);
                            return ;
                        }
                    }
                    updateApp();
                }
                break;
        }
    }
    private void updateApp(){
        HttpManager.getInstance().getUpdate(url, new DownLoadCallBack() {
            @Override
            public void onStart(String s) {
                super.onStart(s);
                btnNeg.setTextColor(context.getResources().getColor(R.color.black_20));
                btnNeg.setClickable(false);
                btnPos.setClickable(false);
                btnPos.setText("正在更新...");
                btnPos.setTextColor(context.getResources().getColor(R.color.tab_red));
            }
            @Override
            public void onProgress(String key, int progress, long fileSizeDownloaded, long totalSize) {
                super.onProgress(key, progress, fileSizeDownloaded, totalSize);
                firstBar.setProgress(progress);
            }
            @Override
            public void onError(Throwable e) {
                Toast.makeText(context, "更新失败", Toast.LENGTH_SHORT).show();
                if(updateForce){
                    ((Activity)context).finish();
                }else{
                    dialog.dismiss();
                }
            }

            @Override
            public void onSucess(String key, String path, String name, long fileSize) {
                MyPerference.getInstance().saveString(Constants.DOWNLOAD_APK,path+name);
                doIntent("file://"+path+name);
            }
        });

    }
    public void doIntent(String url){
        permissionCheck();
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //切记当要同时配Data和Type时一定要用这个方法，否则会出错
        intent.setDataAndType(Uri.parse(url),"application/vnd.android.package-archive");
        context.startActivity(intent);
        ((Activity)context).finish();
    }
    private void permissionCheck(){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            verifyStoragePermissions((Activity) context);
        }
    }
    private static final String[] PERMISSION_EXTERNAL_STORAGE = new String[]{
            Manifest.permission.REQUEST_INSTALL_PACKAGES};

    private void verifyStoragePermissions(Activity activity) {
        int permissionWrite = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.REQUEST_INSTALL_PACKAGES);
        if (permissionWrite != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, PERMISSION_EXTERNAL_STORAGE,
                    100);
        }
    }
}
